package com.zmn.mcc.dubbo.impl.staff;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.zmn.base.plat.engine.common.constant.PlatEngineConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.consts.GlobalConsts;
import com.zmn.gateway.dubbo.client.GUserHolder;
import com.zmn.manager.common.database.annotation.ReadOnlyConnection;
import com.zmn.mcc.business.interfaces.staff.StaffBService;
import com.zmn.mcc.common.constant.DpermitConsts;
import com.zmn.mcc.common.dto.cc.CCStaffDpermitDRO;
import com.zmn.mcc.common.dto.exception.MccException;
import com.zmn.mcc.common.dto.permit.PermitLitDO;
import com.zmn.mcc.common.dto.permit.SpermitDTO;
import com.zmn.mcc.common.dto.staff.LoginStaffDO;
import com.zmn.mcc.common.dto.staff.StaffIdAndDayLimitDRO;
import com.zmn.mcc.dubbo.dto.DubboConsts;
import com.zmn.mcc.dubbo.interfaces.staff.StaffPermitRemoteService;
import com.zmn.mcc.model.entity.dept.McDept;
import com.zmn.mcc.model.entity.organize.McOrganize;
import com.zmn.mcc.model.entity.staff.McStaffDpermit;
import com.zmn.mcc.model.entity.staff.McStaffDpermitQuery;
import com.zmn.mcc.services.interfaces.dept.DeptService;
import com.zmn.mcc.services.interfaces.organize.OrganizeService;
import com.zmn.mcc.services.interfaces.staff.StaffDpermitService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.zmn.mcc.common.constant.DpermitConsts.DEPT_LEVEL_ONE;

/**
 * @author heguanghua
 * @since 2020/06/12 00:41
 */
@Service(version = DubboConsts.INTERFACE_VERSION, validation = "true")
@Slf4j
public class StaffPermitRemoteServiceImpl implements StaffPermitRemoteService {
    private final Logger logger = LoggerFactory.getLogger(StaffPermitRemoteServiceImpl.class);

    private static final String TAG = "权限系统dubbo接口";

    // region Resource

    @Resource
    private StaffBService staffBService;

    @Resource
    private StaffDpermitService staffDpermitService;

    @Resource
    private OrganizeService organizeService;

    @Resource
    private DeptService deptService;
    // endregion


    // region 取得员工功能权限列表

    @Override
    @ReadOnlyConnection
    public SpermitDTO listPermitByLoginStaff(LoginStaffDO loginStaff, Integer sysId) {

        SpermitDTO spermit = staffBService.listPermitByLoginStaff(loginStaff, sysId);

        logger.info(String.format("[%s]取得员工功能权限列表,spermitDTO:[%s]",
                TAG, JSONObject.toJSONString(spermit)));
        return spermit;
    }
    // endregion

    // region 取得员工指定类型的数据权限列表

    @Override
    @ReadOnlyConnection
    public SpermitDTO listDpermitByLoginStaff(LoginStaffDO loginStaff, Integer dataType, Boolean clear) {

        SpermitDTO spermit = staffBService.listDpermitByLoginStaff(loginStaff, dataType, clear);

        logger.info(String.format("[%s]取得员工指定类型的数据权限列表,spermitDTO:[%s]",
                TAG, JSONObject.toJSONString(spermit)));
        return spermit;
    }

    @Override
    public SpermitDTO listDpermitByStaffId(Integer staffId, Integer dataType, Boolean clear) {
        if (staffId == null || dataType == null) {
            return SpermitDTO.fail("参数不能为空");
        }
        return staffBService.listDpermitByStaffId(staffId, dataType, clear);
    }

    @Override
    public ResponseDTO<List<CCStaffDpermitDRO>> listStaffDpermitByUpdateTime(Integer pageSize, Integer pageIndex) {

        if (NumberUtil.isNullOrZero(pageSize)) {
            pageSize = 100;
        }
        if (NumberUtil.isNullOrZero(pageIndex)) {
            pageIndex = 1;
        }
        try {
            McStaffDpermitQuery query = new McStaffDpermitQuery();
            query.setPageSize(pageSize);
            query.setPageIndex(pageIndex);
            List<McStaffDpermit> result = Optional.ofNullable(staffDpermitService.listPageByQuery(query)).orElse(Collections.emptyList());
            List<CCStaffDpermitDRO> result2 = BeanMapper.mapList(result, CCStaffDpermitDRO.class);
            return ResponseDTO.success(result2);
        } catch (BeansException e) {
            log.error("listStaffDpermitByUpdateTime查询失败,原因:{}", e.getMessage(), e);
            return ResponseDTO.fail("查询失败，程序异常");
        }
    }

    /**
     * 描述: 根据员工id集合查询员工查询前溯天数
     *
     * @param staffIdList 员工id集合
     * @return List<StaffIdAndDayLimitDRO>
     * @author xujie
     * @since 2021/05/28
     **/
    @Override
    @ReadOnlyConnection
    public ResponseDTO<List<StaffIdAndDayLimitDRO>> listStaffIdAndDayLimitByStaffIdList(List<Integer> staffIdList) {

        List<StaffIdAndDayLimitDRO> staffIdAndDayLimitList = staffBService.listStaffIdAndDayLimitByStaffIdList(staffIdList);
        return ResponseDTO.success(staffIdAndDayLimitList);
    }

    @Override
    public ResponseDTO<StaffIdAndDayLimitDRO> getCurrentLoginStaffDayLimit() {

        Integer currentLoginStaffId = GUserHolder.getCurrentLoginStaffId();

        List<StaffIdAndDayLimitDRO> staffIdAndDayLimitList = staffBService.listStaffIdAndDayLimitByStaffIdList(Lists.newArrayList(currentLoginStaffId));
        if (CollectionUtils.isEmpty(staffIdAndDayLimitList)) {
            return ResponseDTO.fail("当前用户不存在");
        }

        return ResponseDTO.success(staffIdAndDayLimitList.get(GlobalConsts.NONE));
    }

    @Override
    public SpermitDTO<PermitLitDO> listPermitBySysId(Integer sysId) {

        Integer staffId = GUserHolder.getCurrentLoginStaffId();

        return staffBService.listPermitBySysId(staffId, sysId);
    }

    @Override
    public SpermitDTO<PermitLitDO> listPermitByStaffIdAndSysId(Integer staffId, Integer sysId) {

        return staffBService.listPermitBySysId(staffId, sysId);
    }

    @Override
    public ResponseDTO<List<CCStaffDpermitDRO>> listOrgPermitByStaffIdAndParentId(Integer staffId, Integer parentId) {

        if (parentId == 1) {
            McStaffDpermitQuery query = new McStaffDpermitQuery();
            query.setDataType(DpermitConsts.TYPE_ORGANIZE);
            query.setStaffId(staffId);
            query.setDataParentId(parentId);
            List<McStaffDpermit> list = staffDpermitService.listByQuery(query);
            return ResponseDTO.success(BeanMapper.mapList(list, CCStaffDpermitDRO.class));
        }

        // 判断data_sub_all == 2
        McStaffDpermitQuery query = new McStaffDpermitQuery();
        query.setDataType(DpermitConsts.TYPE_ORGANIZE);
        query.setStaffId(staffId);
        query.setDataParentId(parentId);
        McStaffDpermit mcStaffDpermit = Optional.ofNullable(staffDpermitService.findByQuery(query)).orElseThrow(() -> new MccException("无效的父级ID！"));

        // 返回下级
        if (mcStaffDpermit.getDataSubAll() != 2) {
            McStaffDpermitQuery query2 = new McStaffDpermitQuery();
            query2.setDataType(DpermitConsts.TYPE_ORGANIZE);
            query2.setStaffId(staffId);
            query2.setDataParentId(parentId);
            List<McStaffDpermit> list = staffDpermitService.listByQuery(query);
            return ResponseDTO.success(BeanMapper.mapList(list, CCStaffDpermitDRO.class));
        }

        // 查询其下级数据
        List<McOrganize> mcOrganizes = organizeService.listByParentId(parentId, PlatEngineConsts.STATUS_VALID);
        if (CollectionUtils.isEmpty(mcOrganizes)) {
            return ResponseDTO.success(null);
        }
        List<CCStaffDpermitDRO> result = mcOrganizes.stream().map(x -> {
            CCStaffDpermitDRO ccStaffDpermitDRO = new CCStaffDpermitDRO();
            ccStaffDpermitDRO.setStaffId(staffId);
            ccStaffDpermitDRO.setDataLevel(mcStaffDpermit.getDataLevel() + 1);
            ccStaffDpermitDRO.setDataId(x.getOrgId());
            ccStaffDpermitDRO.setDataName(x.getOrgName());
            return ccStaffDpermitDRO;
        }).collect(Collectors.toList());

        return ResponseDTO.success(result);
    }

    @Override
    public ResponseDTO<List<CCStaffDpermitDRO>> listOrgPermitByStaffIdAndParentIdAndOrgId(Integer staffId, Integer parentId, Integer orgId) {
        // 判断 orgId
        if (Objects.nonNull(orgId)) {
            // 根据
            List<McDept> mcDepts = deptService.listByOrgId(orgId);

            if (CollectionUtils.isEmpty(mcDepts)) {
                return ResponseDTO.success();
            }

            // 查询出所有的部门权限
            McStaffDpermitQuery query = new McStaffDpermitQuery();
            query.setDataType(DpermitConsts.TYPE_DEPT);
            query.setStaffId(staffId);
            query.setDataLevel(DEPT_LEVEL_ONE);
            List<McStaffDpermit> list = staffDpermitService.listByQuery(query);
            if (CollectionUtils.isEmpty(list)) {
                return ResponseDTO.success();
            }

            List<Integer> deptIds = mcDepts.stream().map(McDept::getDeptId).collect(Collectors.toList());

            // 过滤
            List<McStaffDpermit> dpermitList = list.stream().filter(x -> deptIds.contains(x.getDataId())).collect(Collectors.toList());

            return ResponseDTO.success(BeanMapper.mapList(dpermitList, CCStaffDpermitDRO.class));
        }

        if (parentId == 1) {
            McStaffDpermitQuery query = new McStaffDpermitQuery();
            query.setDataType(DpermitConsts.TYPE_DEPT);
            query.setStaffId(staffId);
            query.setDataParentId(parentId);
            List<McStaffDpermit> list = staffDpermitService.listByQuery(query);
            return ResponseDTO.success(BeanMapper.mapList(list, CCStaffDpermitDRO.class));
        }

        // 判断data_sub_all == 2
        McStaffDpermitQuery query = new McStaffDpermitQuery();
        query.setDataType(DpermitConsts.TYPE_DEPT);
        query.setStaffId(staffId);
        query.setDataParentId(parentId);
        McStaffDpermit mcStaffDpermit = Optional.ofNullable(staffDpermitService.findByQuery(query)).orElseThrow(() -> new MccException("无效的父级ID！"));

        // 返回下级
        if (mcStaffDpermit.getDataSubAll() != 2) {
            McStaffDpermitQuery query2 = new McStaffDpermitQuery();
            query2.setDataType(DpermitConsts.TYPE_DEPT);
            query2.setStaffId(staffId);
            query2.setDataParentId(parentId);
            List<McStaffDpermit> list = staffDpermitService.listByQuery(query);
            return ResponseDTO.success(BeanMapper.mapList(list, CCStaffDpermitDRO.class));
        }

        // 查询其下级数据
        List<McDept> mcDepts = deptService.listByParentId(parentId, PlatEngineConsts.STATUS_VALID);
        if (CollectionUtils.isEmpty(mcDepts)) {
            return ResponseDTO.success(null);
        }
        List<CCStaffDpermitDRO> result = mcDepts.stream().map(x -> {
            CCStaffDpermitDRO ccStaffDpermitDRO = new CCStaffDpermitDRO();
            ccStaffDpermitDRO.setStaffId(staffId);
            ccStaffDpermitDRO.setDataLevel(mcStaffDpermit.getDataLevel() + 1);
            ccStaffDpermitDRO.setDataId(x.getDeptId());
            ccStaffDpermitDRO.setDataName(x.getDeptName());
            return ccStaffDpermitDRO;
        }).collect(Collectors.toList());

        return ResponseDTO.success(result);
    }

    public static void main(String[] args) {
        List<String> old = Lists.newArrayList("肖杨眉","张帆","辛晓杰","兰星辰","姚玉喜","宋小龙","袁化克","李兵","刘宗伟","陈大春","吴华军","邓城荣","李小强","殷乾坤","蒲锦飞","陈军","冯波","王魏巍","王强","廖发强","龚义民","马肖","张明","李勇","高振飞","王荣斌","魏甜","杨飞","金四川","刘锋","张英飞","张海宏","武庆福","于福顺","张志义","杨成根","苗玉龙","郭志信","王玉","盛垒","毕磊","叶严浩","孟凡峰","肖龙辉","孙国徽","李自强","潘家阳","邓勇军","李光付","向志","魏蝶","王秀全","刘元亮","张高生","李平锋","杨圆","许术俊","史蒙蒙","徐艺","蒋良斌","卿润伍","杨康","牛鹏松","陈镶鹏","武西宝","胡超","陈义","高磊","杨华","刘兴同","赵建军","位长华","卿路通","马奔红","苏训兵","陈化江","李杰","张乐平","李创奇","李莉","徐番","刘巍巍","丁俊杰","胡国正","周洋","郝传权","郑建平","王伟","冉运学","陈剑涛","杨明昌","谢燕宽","王虎犬","赵汤超","王新涛","王小伟","雷蕾","常永强","葛荣铁","罗仕凯","柯尊春","李进","乔自钊","朱永宏","胡建锋","曾科昌","姚子玉","黄闽","林培养","戴国伟","陈新兵","罗裳根","杜海","林财旺","姚永成","吉小平","张耀宗","潘先义","汪超","张永成","岳东波","李世乾","战厚灿","马润之","马永亮","金燕","王谊谊","鲍邦红","王家春","陶波","林建明","陈涛","石明荣","何银","刘化平","资小雨","张兵","胡涛","黄先华","黄立","曾宪财","黄先荣","刘太福","刘婷","邹建国","黄建","谢孟海","许俊成","张博","左阳春","汪伟","王亮","黄雄群","陈金伍","陈亮","廖炎平","王立保","伍有兴","程坤","汪海军","吴平","朱明鑫","夏绍江","赵志伟","张仕林","夏力稳","沈长玖","王志通","宋哲鸿","涂让传","童亮亮","李源谋","汤金红","刘建琼","廖泽茂","熊大敏","伍强","向世峰","高俊","李雄","刘龙龙","王泽正","文超羿","曾晓平","朱珍辉","文少荣","易美源","袁孝丁","张海兵","杨佳","胡杰金","刘演辉","刘居镇","颜鑫","陈中湘","蔡晓伦","黄亮剑","陈伟民","黄瑾","刘金玉","彭佑平","王朝旭","穆泽波","陈洪中","周训念","杨勇","熊灿林","陈宇","赵仁明","周扩","刘金虹","张海峰","张利","王新","沈禄元","陈培果","魏庆虎","陈晓文","陈保任","张勇","张超","王开波","沈盼","窦英汉","陶其健","李鑫","孙九余","王庆荣","刘洪健","徐彬","王庆福","杨春延","甄澄","陈强","邓利东","刘金宝","李学龙","肖远华","张东","张永发","韩玉国","苏维萍","肖向东","高岩","薛猛","董连有","王志远","马垒","杨宁宁","李一男","林枫","王百胜","何铁良","赵云龙","段承健","王贺斌","陈立纯","李林","王占春","杨戈","凤睿","李岩","邢子龙","闫世杰","李冬冬","王振雷","白俊峰","白玉超","武胜江","姚礼军","房福勇","马亮亮","刘非","张志行","朱亚超","陈光","魏维石","闫世杰","李国强","刘朝民","叶成刚","李剑","赵凤哲","冯雪龙","陈志强","谷明艳","陈征","徐平申","高辉","赵凤哲","蒋苏雨","焦浩然","路文宾","陈旭","唐钢锋","钱明才","陆荣武","胡礼剑","黄治涯","罗富宁","韦德龙","方荣华","王成","华志强","陈涛涛","陈文武","唐天才","苑兴委","赖习忠","梁松林","冯辉","张永","高亨成","王晨霞","肖俊龙","谢真","王允庆","胡相平","李正飞","周明智","谢兆红","王海桃","寇勇","王新","胡定兵","兰伟","李奎","罗霄","彭明","郎佳文","李佳东","桑军利","周永术","田利强","谭挺","代佶伦","王伟","罗仁勇","吴立均","杨佳林","陈烈","张慧群","陈剑","韩伟光","陈秋全","汪彪","宋建华","唐道伟","袁勇","唐明超","唐明超","何西东","于辉","唐远强","蒋怀送","谭伟","高永英","龙涛","汪玉","高龙辉","朱建平","李永辉","唐文菲","马立波","黄功堂","王胜利","左文彬","余建军","陈袁","赖飞","甘润","谭友平","杨程林","王强","罗义力","王磊","赵锋","何俊宁","曹小强","左开佑","唐宗亮","廖海清","张远东","杨仁元","阮玲龙","罗青荣","陈彪","魏鹏辉","刘平","郑月","杨小波","刘志宇","石兴剑","陈胜","李超","邓基波","张昭忠","李宗平","师光光","张冉","高骞","郭培业","张凯","邵聪明","林鑫弘","肖明亮","高皎","王秀娟","杨继峰","陈亚宁","张一丹","王婷","简艳春","曹永平","何雷","张帅帅","陈维森","张策","王健","王继伟","庞大鹏","赵琪","段宏勋","孙贺贺","申君毕","杨立伟","罗云辉","万文浩","保全专","陈万国","贺才文","梁冬波","田波","张梦","李遵华","张杰","刘恩东","刘贵川","莫真享","殷云松","黄群贤","张云兴","黄景华","许周","吴玉众","陈亚","宋孟坤","王雨雷","陈国建","曾繁军","陈吉","杨兴平","刘宇","韦海波","邱忠强","熊义韶","苏德鑫","赵川","刘振","龚发林","冯在宁","李文进","蔡世煌","邢云鹏","史辉吉","万家垒","李德健","黎日童","陈贤鸿","谢兴代","陈彦","郭建群","陈正雄","朱永金","吕林军","周龙","冯令","吴铁刚","冯高伟","郭立刚","罗海涛","梁福健","林杰浩","蓝文威","张须改","江绍禄","邓军","李浩伟","刘俊","姬成希","张浪宏","李天佑","谢春花","康小红","彭雪桃","练培云","沈裕发","彭胜","杨波","杨迪钊","岳兵","邝杰杰","李顺洪","梁高杰","何译注","李国平","马凯","葛金丰","李飞","冉建军","李国平","李顺洪","邹华林","李在成","郑才圣","沈正光","戚铭磊","刘磊","黄道平","丁德康","李恩华","刘超","戚铭磊","邓春雨","张旭东","洪昌波");



        List<String> ne = Lists.newArrayList("马凯","金四川","周训念","蒲锦飞","康小红","杨迪钊","贺才文","高皎","张海宏","陶波","李遵华","张慧群","曾科昌","李莉","张旭东","林建明","冉运学","杨兴平","岳兵","吉小平","陈涛","梁高杰","武西宝","汪彪","陈万国","金燕","陈义","李顺洪","李光付","陈洪中","陈宇","陈大春","王胜利","唐道伟","练培云","王成","万家垒","苑兴委","程坤","邹华林","罗义力","陈彪","刘金玉","丁俊杰","魏维石","李恩华","刘宗伟","黄先华","刘志宇","高振飞","王健","肖龙辉","胡国正","徐艺","李兵","刘金虹","邝杰杰","杨仁元","罗裳根","徐番","林杰浩","唐天才","刘超","林培养","陈中湘","黄立","高永英","田利强","赵汤超","吴平","梁松林","叶成刚","冯令","李创奇","陈培果","谢燕宽","胡涛","蒋良斌","王强","李小强","左开佑","吴华军","夏绍江","袁化克","蔡晓伦","冉建军","孙国徽","乔自钊","朱珍辉","周龙","魏甜","赖习忠","石明荣","何银","马润之","李文进","张兵","丁德康","朱永金","唐明超","杨勇","姚永成","向志","杨飞","冯雪龙","张利","吴铁刚","袁勇","陈剑涛","邓勇军","王家春","刘居镇","张须改","蓝文威","李勇","穆泽波","黄治涯","战厚灿","邓城荣","王强","陈秋全","龙涛","高龙辉","潘先义","甘润","梁冬波","宋建华","谭伟","王伟","冯辉","资小雨","蒋怀送","冯波","何西东","唐文菲","张策","胡超","吕林军","陈维森","王谊谊","陈军","沈长玖","许周","张帅帅","谷明艳","刘宇","沈裕发","何译注","韩玉国","黄功堂","陈胜","张博","陈文武","张仕林","甄澄","雷蕾","谭友平","马润之","王魏巍","罗仕凯","乔自钊","罗义力","阮玲龙","文少荣","王庆荣","王继伟","梁福健","邢子龙","蔡世煌","万文浩","易美源","杨立伟","韩伟光","王秀娟","王荣斌","李自强","冯高伟","郭立刚","周洋","郑建平","姚子玉","申君毕","陈剑","彭胜","胡相平","张永","杨圆","杨继峰","陈亚宁","肖远华","李莉","王婷","高皎","许术俊","李德健","谢兴代","胡礼剑","殷乾坤","马肖","张志义","袁孝丁","李冬冬","史蒙蒙","王虎犬","张一丹","高辉","陈新兵","高亨成","郑月","马立波","李岩","葛金丰","赵凤哲","李学龙","徐彬","张海峰","汪玉","龚义民","廖发强","熊灿林","柯尊春","余建军","赖飞","陈袁","张永成","彭雪桃","李奎","兰伟","肖俊龙","罗海涛","李平锋","陈志强","罗青荣","张耀宗","刘巍巍","冯雪龙","彭明","谢兆红","周明智","沈盼","王秀全","王晨霞","陈伟民","沈正光","戚铭磊","赵志伟 ","邓利东","陈强","王志远","钱明才","谢春花","葛荣铁","颜鑫","李剑","魏蝶","陈大春","左文彬","杨春延","路文宾","唐钢锋","陶其健","周扩","罗霄 ","蒋苏雨","肖向东","王百胜","李一男","林枫","凤睿","杨佳","黄瑾","冯在宁","谢孟海","邹建国","赵锋","赵川","刘演辉","石兴剑","陈亚","曾繁军","陈国建","汪海军","朱明鑫","董连有","张东","苏维萍","焦浩然","王雨雷","朱建平","于辉","韩伟光","常永强","朱永宏","李永辉","宋孟坤","张永发","汪超","邢云鹏","王新","李国强","马永亮","窦英汉","罗云辉","刘兴同","姚礼军","刘元亮","段宏勋","庞大鹏","赵琪","赵仁明","李世乾","杨波","武庆福","周永术","刘振","龚发林","陈正雄","岳东波","陈吉","杜海","戴国伟","陈化江","马奔红","兰星辰","辛晓杰","何俊宁","魏庆虎","陈涛涛","谭挺","刘化平","赵建军","卿润伍","张冉","师光光","李宗平","高骞","郭培业","叶严浩","潘家阳","刘贵川","刘恩东","莫真享","黄亮剑","王海桃","罗仁勇","邓春雨","黄道平","杨宁宁","杨明昌");


        old.removeAll(ne);

        System.out.println(old);

    }
}
